import { CustomPage, CustomTable, TagView } from '@/components/index.jsx';
import { LIMIT } from '@/constants/pageConstant.js';
import ModalUtil from '@/utils/modal.js';
import { Avatar, Button, Card, Flex, Form, Input, InputNumber } from 'antd';
import { UserApi } from '@/api/user/api.js';
import { useEffect, useRef, useState } from 'react';
import { SPACE } from '@/constants/themeConstant.js';
import UserFormModal from '@/pages/UserManage/widget/UserFormModal/index.jsx';
import UserStatus from '@/pages/UserManage/widget/UserStatus/index.jsx';
import useQqAvatar from '@/hooks/useQqAvatar.js';
import SearchForm from '@/components/SearchForm/index.jsx';
import ChangePasswordModal from '@/pages/UserManage/widget/ChangePasswordModal/index.jsx';
import { FORBIDDEN_USER_IDS } from '@/constants/CommonConstant.js';
import StringUtil from '@/utils/string.js';

// 表格选中项
const rowSelection = {
  type: 'checkbox',
  fixed: true
};

export default function UserManage() {
  // 表格
  const tableRef = useRef();
  // 搜索条件
  const [searchQuery, setSearchQuery] = useState();
  // 表单弹窗
  const formRef = useRef();
  // 修改密码弹窗
  const changePasswordRef = useRef();
  // 获取QQ头像
  const qqAvatar = useQqAvatar('2327972001');

  useEffect(() => {
    if (searchQuery) {
      tableRef.current?.request();
    }
  }, [searchQuery]);

  // 请求数据
  async function getData(options) {
    // 解构条件
    const { pagination, sorter } = options;
    // 页码
    const pageNo = pagination?.current || 1;
    // 页大小
    const pageSize = pagination?.pageSize || LIMIT;
    // 排序字段
    const sortField = StringUtil.toSnakeCase(sorter?.field);
    // 排序方式
    const sortOrder = sorter?.order === 'ascend';
    const { data } = await UserApi.getUserList(pageNo, pageSize, searchQuery, sortField, sortOrder);
    const { list, total } = data;
    return Promise.resolve({
      data: list,
      success: true,
      total: total
    });
  }

  function handleDelete(selectedRows) {
    if (selectedRows.length === 0) {
      ModalUtil.warn('请选择要删除的用户');
      return;
    }
    ModalUtil.confirm(
      `确定要删除: ${selectedRows.map((row) => row.username).join('、')} 吗？`,
      async () => {
        const ids = selectedRows.map((row) => row?.userId);
        await UserApi.deleteByIds(ids).then(({ code }) => {
          if (code === 0) {
            ModalUtil.success('删除成功');
            tableRef?.current?.request();
            tableRef.current?.setSelectedRows(
              tableRef.current?.selectedRows?.filter((row) => !ids.includes(row.userId))
            );
          }
        });
      }
    );
  }

  function onEdit(data) {
    formRef.current?.openEdit(data);
  }

  function onAdd() {
    formRef.current?.openAdd();
  }
  function handleChangePassword(data) {
    changePasswordRef.current?.open(data);
  }

  return (
    <CustomPage>
      <UserFormModal
        ref={formRef}
        onRefresh={() => {
          tableRef?.current?.request();
        }}
      />
      <ChangePasswordModal
        ref={changePasswordRef}
        onRefresh={() => {
          tableRef?.current?.request();
        }}
      />
      <Card>
        <Flex vertical gap={SPACE}>
          {renderToolbar()}
          <CustomTable
            ref={tableRef}
            rowKey="userId"
            title="用户列表"
            optionsWidth={45}
            onRowDelete={(row) => {
              handleDelete([row]);
            }}
            onDelete={handleDelete}
            hideDelete={(row) => {
              return FORBIDDEN_USER_IDS.includes(row?.userId);
            }}
            onAdd={onAdd}
            onRowEdit={onEdit}
            onEdit={onEdit}
            rowSelection={rowSelection}
            columns={getColumns()}
            request={getData}
            getOptions={(row) => [
              <Button
                key="change-password-operation"
                type="primary"
                onClick={() => handleChangePassword(row)}
                size="small"
              >
                修改密码
              </Button>
            ]}
          />
        </Flex>
      </Card>
    </CustomPage>
  );

  // 渲染工具栏
  function renderToolbar() {
    const width = 150;
    return (
      <>
        <SearchForm
          onSearch={(values) => {
            tableRef.current?.setPageNo(1);
            setSearchQuery(values);
          }}
          formItems={
            <>
              <Form.Item label="用户ID" name="userId">
                <InputNumber min={1} placeholder="请输入用户ID" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="用户名" name="username">
                <Input placeholder="请输入用户名" style={{ width: width }} />
              </Form.Item>
            </>
          }
        />
      </>
    );
  }

  // 表格列
  function getColumns() {
    return [
      {
        title: '用户ID',
        dataIndex: 'userId',
        key: 'userId',
        sorter: true
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username'
      },
      {
        title: '头像',
        dataIndex: 'avatar',
        key: 'avatar',
        render: (value) => {
          return <Avatar src={value ?? qqAvatar} size={32} />;
        }
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        key: 'nickname'
      },
      {
        title: '角色',
        dataIndex: 'roleList',
        key: 'roleList',
        render: (roleList) => {
          if (!Array.isArray(roleList)) {
            return '-';
          }
          return <TagView tags={roleList.map((o) => o?.roleName)} />;
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (value) => {
          return <UserStatus status={value} />;
        }
      },
      {
        title: '封禁时间',
        dataIndex: 'suspendedTime',
        key: 'suspendedTime',
        sorter: true
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        sorter: true
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        sorter: true
      }
    ];
  }
}
